package de.bib.blue.manage.finance;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import de.bib.blue.manage.finance.database.ResourceDatabase;
import de.bib.blue.manage.finance.dialog.LoginDialog;
import de.bib.blue.manage.finance.parser.LoadFile;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
	 * IApplicationContext)
	 */
	public Object start(IApplicationContext context) {
		Display display = PlatformUI.createDisplay();
		try {

			if (!login(display)) {
				return IApplication.EXIT_OK;
			}

			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IApplication.EXIT_RESTART;
			}
			return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}
	}

	private boolean login(Display display) {
		Shell shell = display.getActiveShell();

		ResourceDatabase database = null;
		try {
			/*
			 * Mencoba koneksi dengan database.
			 */
			database = ResourceDatabase.getInstance();
			LoadFile f = new LoadFile(database);

			f.loadsFile();

		} catch (Exception e) {
			System.out.println(e);
			/*
			 * Jika tidak dapat terhubung ke database.
			 */
			String title = "Login";
			String message = "Cannot connect to database";

			MessageDialog.openError(shell, title, message);
			return false;
		}

		Exception e = null;
		int attempts = 0;

		while (true) {
			LoginDialog dialog = new LoginDialog(shell, e, attempts);
			if (dialog.open() == LoginDialog.OK) {
				String userName = dialog.getUsername();
				String password = dialog.getPassword();

				if (database.login(userName, password)) {
					return true;
				}

				attempts++;
			} else {
				return false;
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
}
